import re
from typing import List, Tuple
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageSegment
from nonebot.exception import FinishedException
# 创建命令处理器
nickname_checker = on_command("查看群名片", priority=10)
test_command = on_command("测试", priority=10)

# 定义群名片格式：班级+数字+姓名，例如：计科241石豪瑞
NICKNAME_PATTERN = re.compile(r'^(.+?)(\d+)(.+)$')

@nickname_checker.handle()
async def handle_nickname_check(bot: Bot, event: GroupMessageEvent):
    """处理查看群名片命令"""
    print(f"[DEBUG] 收到群名片检查命令，群号: {event.group_id}, 用户: {event.user_id}")
    print(f"[DEBUG] 命令处理器优先级: 10")
    try:
        # 获取群成员列表
        group_id = event.group_id
        member_list = await bot.get_group_member_list(group_id=group_id)
        
        if not member_list:
            await nickname_checker.finish("无法获取群成员列表")
            return
        
        # 检查每个群成员的群名片
        invalid_members = []
        valid_members = []
        
        for member in member_list:
            user_id = member['user_id']
            card = member.get('card', '')
            nickname = member.get('nickname', '')
            actual_nickname = card or nickname
            
            print(f"[DEBUG] 成员 {user_id}: card='{card}', nickname='{nickname}', 实际使用='{actual_nickname}'")
            
            if not actual_nickname:
                invalid_members.append((user_id, actual_nickname, "未设置群名片"))
                continue
            
            # 检查群名片格式（使用实际使用的群名片）
            is_valid = is_valid_nickname_format(actual_nickname)
            print(f"[DEBUG] 群名片 '{actual_nickname}' 格式检查结果: {is_valid}")
            
            if is_valid:
                valid_members.append((user_id, actual_nickname))
            else:
                invalid_members.append((user_id, actual_nickname, "格式不符合要求"))
        
        # 生成检查结果消息
        result_message = generate_check_result_message(valid_members, invalid_members)
        
        # 发送结果
        await nickname_checker.finish(result_message)
        
    except FinishedException:
        # 让 FinishedException 正常传递，不记录为错误
        raise
    except Exception as e:
        print(f"[ERROR] 检查群名片时发生错误: {str(e)}")
        import traceback
        traceback.print_exc()
        await nickname_checker.finish(f"检查群名片时发生错误: {str(e)}")

@test_command.handle()
async def handle_test(bot: Bot, event: GroupMessageEvent):
    """测试命令处理器"""
    print(f"[DEBUG] 收到测试命令，群号: {event.group_id}, 用户: {event.user_id}")
    await test_command.finish("插件正常工作！")

def is_valid_nickname_format(nickname: str) -> bool:
    """
    检查群名片格式是否符合要求
    格式要求：班级+数字+姓名，例如：计科241石豪瑞
    """
    if not nickname or len(nickname.strip()) == 0:
        return False
    
    # 使用正则表达式匹配格式
    match = NICKNAME_PATTERN.match(nickname.strip())
    if not match:
        return False
    
    class_name = match.group(1).strip()
    number = match.group(2).strip()
    name = match.group(3).strip()
    
    # 检查各部分是否都不为空
    if not class_name or not number or not name:
        return False
    
    # 检查数字部分是否全为数字
    if not number.isdigit():
        return False
    
    # 检查姓名部分是否包含中文字符（简单检查）
    if not re.search(r'[\u4e00-\u9fff]', name):
        return False
    
    return True

def generate_check_result_message(valid_members: List[Tuple[int, str]], invalid_members: List[Tuple[int, str, str]]):
    """生成检查结果消息，使用MessageSegment构建"""
    message_parts = []
    
    # 添加统计信息
    total_count = len(valid_members) + len(invalid_members)
    valid_count = len(valid_members)
    invalid_count = len(invalid_members)
    
    message_parts.append(MessageSegment.text(f"📋 群名片检查结果\n"))
    message_parts.append(MessageSegment.text(f"总人数: {total_count}\n"))
    message_parts.append(MessageSegment.text(f"✅ 格式正确: {valid_count} 人\n"))
    message_parts.append(MessageSegment.text(f"❌ 格式错误: {invalid_count} 人\n\n"))
    
    # 添加格式说明
    message_parts.append(MessageSegment.text("📝 群名片格式要求：班级+数字+姓名\n"))
    message_parts.append(MessageSegment.text("示例：计科241小依\n\n"))
    
    # 添加错误成员列表
    if invalid_members:
        message_parts.append(MessageSegment.text("❌ 需要修改群名片的成员：\n"))
        for user_id, nickname, reason in invalid_members:
            # 使用MessageSegment.at进行真正的艾特
            message_parts.append(MessageSegment.at(user_id))
            if nickname:
                message_parts.append(MessageSegment.text(f" - {reason}\n"))
            else:
                message_parts.append(MessageSegment.text(f" - {reason}\n"))
        message_parts.append(MessageSegment.text("\n请按照格式要求修改群名片！"))
    else:
        message_parts.append(MessageSegment.text("🎉 所有成员的群名片格式都正确！"))
    
    return message_parts
